<template>
	<view class="track">
		<view class="title">
			<icon class="iconfont icon-31fanhui1 go-back" @tap="goBack"></icon>
			<text class="title-t">{{markInfo.name}}的足迹</text>
		</view>
		<map
			id="track-map"
			style="width: 100%; height: 100%;" 
			:latitude="coords.lat" 
			:longitude="coords.lng"
			:scale="coords.scale"
			@regionchange="mapChange"
			@markertap="markerClick"
			:markers="markers"
			:polyline="polyline">
		</map>
		<view class="picker">
			<picker @change="bindPickerChange" :value="markDateObj.i" :range="markDateObj.a">
				<text>{{markDateObj.a[markDateObj.i]}}</text>
			</picker>
		</view>
		<!-- marker详细内容 -->
		<uni-popup ref="POP_UP_MARKER" mask-background-color="rgba(0,0,0,0)" @tap="popUpAction('')">
			<view v-if="popUpFlag == 'marker-card'">
				<marker-card :data="markerCardData"></marker-card>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { onMounted,ref,reactive,nextTick  } from "vue"
import { onLoad } from "@dcloudio/uni-app"
import request from "../../util/request.js"
import util from "../../util/util.js"
import userInfo from "../../hooks/userInfo.js"
import MarkerCard from "../../components/fun_coms/markercard.vue"
	export default {
		components: {
			MarkerCard
		},
		setup() {
			onLoad((q)=>{
				if (util.isNull(q)) {
					q.id = user.openId
					q.name = '我'
				}
				markDateObj.a =  uni.getStorageSync('markDateArr') || []
				q.date = util.dateFormatStr(markDateObj.a[0])
				markInfo.value = q
				setMarkMap(markInfo.value)
			})
			// mark日期对象
			let markDateObj = reactive({
				i: 0,
				a: []
			})
			function bindPickerChange(e) {
				let i = e.detail.value
				markDateObj.i = i
				markInfo.value.date = util.dateFormatStr(markDateObj.a[i])
				setMarkMap(markInfo.value)
			}
			// 当前用户
			let user = userInfo()
			// 地图对象
			let mapctx = uni.createMapContext('track-map',this)		
			let coords = reactive({
				lat: 41.769465,
				lng: 123.427158,
				scale: 14,
			})
			
			// 按日期查询打卡记录
			let markInfo = ref({name: ''})
			let markers = ref([])
			let polyline = ref([])
			async function setMarkMap(q) {
				let g = {}
				g.openId = q.id
				g.sTime = q.date+' 00:00:00'
				g.eTime = q.date+' 23:59:59'
				// console.log(g)
				let r = await request.getMarks(g)
				if (r.code == 10000) {
					let _data = r.data
					let _markers = []
					let _joinCluster = _data.length >= 9
					for (let i in _data) {
						let m = {}
						m.recId = _data[i]._id
						m.id = i*1+1
						m.latitude = _data[i].latitude
						m.longitude = _data[i].longitude
						m.title = _data[i].title
						m.adress = _data[i].address
						m.iconPath = '/static/imgs/marker.png'
						m.markDT = util.formatGmt(_data[i].markTime)
						m.width = 42
						m.height = 42
						m.callout = {}
						m.callout.content = m.markDT.split(' ')[1]+'\n'+m.title
						m.callout.borderRadius = '5px'
						m.callout.bgColor = '#cccccc99'
						m.callout.padding = '5px'
						m.callout.display = 'ALWAYS'
						m.joinCluster = _joinCluster
						_markers.push(m)
					} 
					markers.value = _markers
					if (!util.isNull(_markers)) {
						// initPolyline()
						coords.lat = _markers[0].latitude
						coords.lng = _markers[0].longitude
						initMarkerCluster()
						mapctx.includePoints({
						  points:_markers,
						  padding:[100,100,100,100],          
						  success: function (e) {
								console.log(e)
							}
						})
					}
				}
			}
			// 自定义点聚合格式
			function initMarkerCluster() {
				mapctx.initMarkerCluster({
					enableDefaultStyle:false,
					zoomOnClick:true,
					gridSize:60,
				})
				mapctx.on('markerClusterCreate',res=>{
					const clusters = res.clusters
					const markers = clusters.map(cluster => {
						const {center,clusterId,markerIds} = cluster
						return {
							...center,
							clusterId, 
							width: 1,
							height: 1,
							// iconPath: '/static/imgs/marker.png',
							joinCluster: true,
							label: {
								content: markerIds.length + '',  
						    fontSize: 20, 
						    color: '#111',  
						    width: 50,  
						    height: 50,  
						    bgColor: '#ffd303',  
						    borderRadius: 25,  
								borderWidth: 1,
								borderColor: '#ccc',
						    textAlign: 'center',  
						    anchorX: -25,  
						    anchorY: -50,  
							}
						}
					})
					mapctx.addMarkers({
						markers,
						clear: false,
						complete(res) {
							console.log('clusterCreate addMarkers', res)
						}
					})
				})
			}
			// 监听地图范围大小
			function mapChange(e) {
				// console.log(e)
				let _scale = e.detail.scale
				let _markers = markers.value
				if (_scale >= 20) {
					for (let i in _markers) {
						_markers[i].joinCluster = _scale <= 21
					}
					markers.value = _markers
				}
			}
			// 点击marker
			function markerClick(e) {
				let _id = e.markerId
				let _markers = markers.value
				let marker = null
				for(let i in _markers) {
					if (_id == _markers[i].id) {
						marker = _markers[i]
					}
				}
				if (marker.latitude && marker.longitude) {
					mapctx.moveToLocation({
						latitude: marker.latitude,
						longitude: marker.longitude,
						success: (res) => {
							if (_id == 0) {
								return
							}
							getMarksDetail(marker)
						},
						fail: (err) => {
							console.log(err)
						}
					})
				}
			}
			// 查询marker明细数据
			async function getMarksDetail(m) {
				let _markers = markers.value
				let recIds = []
				for (let i in _markers) {
					if (m.latitude == _markers[i].latitude && m.longitude == _markers[i].longitude) {
						recIds.push(_markers[i].recId)
					}
				}
				let g = {}
				g.openId = markInfo.value.id
				g.recIds = JSON.stringify(recIds)
				let r = await request.getMarksById(g)
				if (r.code == 10000) {
					markerCardData.markers = r.data
					markerCardData.flag = 'marker-readonly'
					popUpAction('marker-card')
				}
			}
			// 显示markercard
			let POP_UP_MARKER = ref(null)
			let popUpFlag = ref('')
			function popUpAction(f) {
				if (f == 'marker-card') {
					popUpFlag.value = f
					POP_UP_MARKER.value.open('top')
				} else {
					POP_UP_MARKER.value.close()
					setTimeout(function() {
						popUpFlag.value = ''
					}, 150);
				}
			}
			
			// markerCard数据
			let markerCardData = reactive({
				marker: {}, 
				flag: ''
			})
			
			// 生成足迹路线
			function initPolyline() {
				polyline.value = []
				let mks = markers.value
				if (mks.length == 0) return
				let _polyline= {}
				_polyline.points = []
				for (let i in mks) {
					let point = {}
					point.latitude = mks[i].latitude
					point.longitude = mks[i].longitude
					_polyline.points.push(point)
				}
				_polyline.color = "#FA6400"
				_polyline.width = 8
				_polyline.arrowLine = true
				_polyline.borderWidth = 1
				_polyline.borderColor = '#ccc'
				polyline.value.push(_polyline)
				// 如需获取更精确的轨迹，需要申请onLocationChange接口
			}
			
			// 返回上一页
			function goBack() {
				uni.navigateBack()
			}
			let testStr = ref('testStr')
			return {
				coords,markInfo,markers,polyline,mapChange,markerClick,
				POP_UP_MARKER,popUpFlag,markerCardData,popUpAction,
				goBack,markDateObj,bindPickerChange,testStr
			}
		}
	}
</script>

<style lang="scss" src="./track.scss"></style>
